﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using IM.GUI.Widgets.ExtensionNodes;
using IM.Interfaces;
using IM.Interfaces.Protocols;
using System.Threading;

namespace IM.GUI.Widgets.Settings
{
    public partial class Settings : UserControl
    {
        private SynchronizationContext uiContext;
        private ICore core;

        public Settings()
        {
            uiContext = WindowsFormsSynchronizationContext.Current;
            InitializeComponent();

            this.imageList1.Images.Add((Image)global::IM.GUI.Widgets.Properties.Resources.jabber);
            this.listAccounts.DoubleClick += new EventHandler(listAccounts_DoubleClick);
        }

        void listAccounts_DoubleClick(object sender, EventArgs e)
        {
            this.tabControl1.SelectedTab = this.tabControl1.TabPages[(sender as ListView).SelectedItems[0].Text];
        }

        public Button SaveButton
        {
            get { return this.btnSave; }
        }

        public Button CancelButton
        {
            get { return this.btnCancel; }
        }

        public void LoadProtocolControls(ICore core)
        {
            uiContext.Send(new SendOrPostCallback(delegate(object state)
            {
                this.core = core;

                while (this.tabControl1.TabCount > 1) 
                    this.tabControl1.TabPages.RemoveAt(1);

                this.listAccounts.Items.Clear();

                for (int i = 0; i < core.ProtocolManager.Count; i++)
                {
                    IProtocolAdapter adapter = core.ProtocolManager[i];

                    this.listAccounts.Items.Add(adapter.Protocol.AccountName, adapter.Protocol.AccountName, 0);
                    

                    AddProtocolToTab(adapter);
                }
            }), null);
        }

        private void AddProtocolToTab(IProtocolAdapter adapter)
        {
            IProtocol protocol = adapter.Protocol;
            IProtocolSettings settings = adapter.Settings;
            Control c = settings.GetSettingsControl();
            c.Dock = DockStyle.Fill;

            this.tabControl1.TabPages.Add(adapter.Protocol.AccountName, protocol.AccountName);

            TabPage page = this.tabControl1.TabPages[protocol.AccountName];
            page.Tag = adapter;
            page.Controls.Add(c);
        }

        private void linkAdd_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            String protocolPath = this.core.Settings.Paths[SpecialPaths.ProtocolsPath];

            IProtocolAdapter[] adapters = null;
			try
			{
				adapters = this.core.ProtocolManager.GetAvaibleProtocols(protocolPath);
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "Error while loading available protocols.", MessageBoxButtons.OK, MessageBoxIcon.Error);
				Logging.Logger.AddException(ex);
				return;
			}

            this.ctxProtocols.Items.Clear();

            foreach (var adapter in adapters)
            {
                ToolStripItem item = this.ctxProtocols.Items.Add(adapter.Protocol.ProtocolName);
                item.Tag = adapter;
                item.Click += new EventHandler(item_Click);
            }

            this.ctxProtocols.Show(this.linkAdd, new System.Drawing.Point(0, 22));
            this.Invalidate();
        }

        void item_Click(object sender, EventArgs e)
        {
            IProtocolAdapter adapter = (sender as ToolStripItem).Tag as IProtocolAdapter;

            //AddProtocolToTab(adapter);

            this.core.ProtocolManager.CreateProtocol(adapter);

            LoadProtocolControls(this.core);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < this.core.ProtocolManager.Count; i++)
            {
                String name = this.core.ProtocolManager[i].Protocol.AccountName;
                
                if (!this.listAccounts.Items.ContainsKey(name))
                    this.core.ProtocolManager.DestroyProtocol(name);
            }

            for (int i=0; i < this.core.ProtocolManager.Count; i++)
            {
                try
				{
                	IProtocolAdapter adapter = this.core.ProtocolManager[i];
	                Object obj = adapter.Settings.GetSettingsData(adapter.Protocol.GetSettingsData());
	                String name = adapter.Protocol.AccountName;
	                
	                this.core.Settings.ProtocolsSettings[name] = obj;
                } 
				catch (Exception ex) 
				{
					Logging.Logger.AddException(ex);
                	MessageBox.Show("Unexpected exception occured while saving yout settins.\n" + ex.Message, "There was an error saving protocol settins!",
					                MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            this.core.Settings.Save();

            if (this.ParentForm != null)
                this.ParentForm.DialogResult = DialogResult.OK;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (this.ParentForm != null)
                this.ParentForm.DialogResult = DialogResult.Cancel;
        }

        private void removeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.ListView.SelectedListViewItemCollection items = this.listAccounts.SelectedItems;

            if (items.Count > 0)
            {
                String name = items[0].Text;
                TabPage page = this.tabControl1.TabPages[name];

                this.core.Settings.ProtocolsSettings.Remove(name);
                this.tabControl1.TabPages.Remove(page);
                this.listAccounts.Items.RemoveByKey(name);
            }
        }


    }
}
